package com.ivan.toolkit.network;

import java.net.DatagramPacket;
import java.net.InetSocketAddress;

import org.json.JSONObject;

import com.google.common.base.Charsets;

import lombok.extern.log4j.Log4j2;

@Log4j2
public abstract class JsonUDP extends UdpClient {
	
	public static final String HostKey = "_HOST_";
	
	public static final String PortKey = "_PORT_";


	@Override
	public void dispatch(DatagramPacket packet) {
		
		try {
		
			byte[] data = packet.getData();
			
			String txt = new String(data, Charsets.UTF_8);
			
			JSONObject json = new JSONObject(txt);
			
			dispatch(packet.getAddress().getHostAddress(), packet.getPort(), json);
		
		} catch(Exception e) {
			
			log.error("Parse json data failed.", e);
			
		}
				
	}
	
	public abstract void dispatch(String host, int port, JSONObject value);
	
	public void post(String host, int port, JSONObject value) {
		
		try {
		
			String txt = value.toString();
			
			byte[] data = txt.getBytes(Charsets.UTF_8);
			
			DatagramPacket packet = new DatagramPacket(data, data.length);
			
			packet.setSocketAddress(new InetSocketAddress(host, port));
			
			this.socket.send(packet);
		
		} catch(Exception e) {
			
			log.error("Send json data failed.", e);
			
		}
		
	}

}
